<?php

namespace yunj\app\admin\validate\member;

use yunj\app\admin\enum\State;
use yunj\app\admin\validate\Validate;

class LoginValidate extends Validate {

    protected $rule = [
        "data" => "require",
    ];

    protected $message = [
        'data.require' => '参数错误',
    ];

    protected $scene = [
        'Login' => ['data']
    ];

    protected function handleData(array &$data, $scene): void {
        switch ($scene) {
            case 'Login':
                $this->handleDataByLogin($data);
                break;
        }
    }

    private function handleDataByLogin(&$data): void {
        $this->handleDataByLoginFormData($data);
        ['username' => $username, 'password' => $password, 'captchaCode' => $captchaCode, 'captchaHash' => $captchaHash] = $data;
        // username
        if (!$username) throw_error_json('账户不能为空');
        if (!is_string($username) || !$this->regex($username, 'alphaDash') || strlen($username) > 64) throw_error_json('账户或密码错误');
        // password
        if (!$password) throw_error_json('密码不能为空');
        if (!is_string($password) || !$this->regex($password, 'alphaDash')) throw_error_json('账户或密码错误');
        // captchaCode
        if (!$captchaCode) throw_error_json('验证码不能为空');
        if (!is_string($captchaCode) || !$captchaHash || !is_string($captchaHash) || !yunj_captcha()->check($captchaCode, $captchaHash)) throw_error_json('验证码错误');

        // member
        $member = self::getAdminMemberModel()->with('roles')
            ->where([
                ['username', '=', $username],
                ['state', '<>', State::DELETED],
            ])->find();
        if (!$member) throw_error_json("账户或密码错误");
        if ($member->state != State::NORMAL) throw_error_json("账户已冻结");
        if (!$member->roles) throw_error_json("当前账户未分配有效角色");
        list($passwordHash, $passwordSalt) = password_handle($password, $member->password_salt);
        if ($passwordHash !== $member->password_hash) throw_error_json("账户或密码错误");
        $data["member"] = $member;
    }

    private function handleDataByLoginFormData(&$data): void {
        if (!is_string($data['data'])) throw_error_json('参数错误');
        $dataArr = json_decode(urldecode($data['data']), true);
        $encrypt = $dataArr['data'];
        $key = $dataArr['key'];
        $iv = $dataArr['iv'];
        $decrypt = aes_decrypt($encrypt, $key, $iv);
        [
            'username' => $data['username'],
            'password' => $data['password'],
            'captchaCode' => $data['captchaCode'],
            'captchaHash' => $data['captchaHash']
        ] = json_decode($decrypt, true);
    }

}